//
//  PokerTexasHoldem.h
//  CPokerTexasHoldem: Main class of poker texas holde'm game
//
//  Created by Enric Vergara on 27.06.10. 
//  Copyright OWLAB 2010. All rights reserved.
//

// Import the interfaces
#import "PokerTexasHoldem.h"
#import "LocalPlayer.h"
#import "NetworkPlayer.h"
#import "AIPlayer.h"
#import "SoundManager.h"


#define NUM_PLAYERS_MAX 10

//comentar això per tal que no debugar les cartes dels players
#define DEBUG_GAME_POKER

// CPokerTexasHoldem implementation
@implementation CPokerTexasHoldem

+(id) scene
{
	// 'scene' is an autorelease object.
	CCScene *scene = [CCScene node];
	
	// 'layer' is an autorelease object.
	CPokerTexasHoldem *layer = [CPokerTexasHoldem node];
	
	// add layer as a child to scene
	[scene addChild: layer];
	
	// return the scene
	return scene;
}

// on "init" you need to initialize your instance
-(id) init
{
	// always call "super" init
	// Apple recommends to re-assign "self" with the "super" return value
	if ((self = [super init]))
    {
        m_ConditionGame = [[CConditionGame alloc] init];
        m_bFirstBet = true;
        m_bButtonPressed_NewHand = false;
        [self changeState:PokerState_NewHand];
        m_StateMachine.m_ePopGameState = PokerState_Max;
        m_uiBank = 0;
        CGSize screenSize = [[CCDirector sharedDirector] winSize];
        m_pBoard = [[CBoard alloc] init];
        m_pBoard->screenSize = screenSize;
        m_pDeck = [[CDeck alloc] init];
        [m_pBoard setCBoardEnviroment];
        [self addChild:m_pBoard];
        m_uiNumplayers = 0;
        [self initPosPlayers];
        
        
        //------INSERT PLAYERS--------------------------------
        //[self addPlayer:PokerPlayer_AI Name:@"AI Plauer 1"];
        [self addPlayer:PokerPlayer_Local Name:@"Local Player 1"];
        //[self addPlayer:PokerPlayer_AI Name:@"AI Plauer 2"];
        [self addPlayer:PokerPlayer_Local Name:@"Local Player 2"];
        [self addPlayer:PokerPlayer_Local Name:@"Local Player 3"];
        [self addPlayer:PokerPlayer_Local Name:@"Local Player 4"];
        //[self addPlayer:PokerPlayer_Network Name:@"Network Player 4"];
        [self setPlayerButtons];
        //----------------------------------------------------
        
        
        
        //------CONFIGURE LABELS------------------------------
        //label indicant l'estat del joc
        m_StateMachine.m_sStateLabel = [CCLabel labelWithString: NSLocalizedString(@"PokerState_NewHand", @"") 
                                                       fontName:@"Arial" fontSize:24];
        [m_StateMachine.m_sStateLabel setColor:ccc3(0,0,0)];
        [m_StateMachine.m_sStateLabel setPosition:CGPointMake(screenSize.width/2, screenSize.height/2+105)];
        [self addChild: m_StateMachine.m_sStateLabel];
        
        
        //label indicant l'estat de la banca
        m_sBankLabel = [CCLabel labelWithString: @"Bank: 0 $" fontName:@"Arial" fontSize:24];
        [m_sBankLabel setString:[NSString stringWithFormat:@"%@%d $",NSLocalizedString(@"Bank", @""), m_uiBank]];
        [m_sBankLabel setColor:ccc3(0,0,0)];
        [m_sBankLabel setPosition:CGPointMake(screenSize.width/2 - 100, screenSize.height/2+130)];
        [self addChild: m_sBankLabel];

        //label indicant l'estat de la current bet
        m_sCurrentBetLabel = [CCLabel labelWithString: @"CurrentBet: 0 $" fontName:@"Arial" fontSize:24];
        [m_sCurrentBetLabel setString:[NSString stringWithFormat:@"%@%d $",NSLocalizedString(@"CurrentBet", @""), m_uiCurrentBet]];
        [m_sCurrentBetLabel setColor:ccc3(0,0,0)];
        [m_sCurrentBetLabel setPosition:CGPointMake(screenSize.width/2 + 100, screenSize.height/2+130)];
        [self addChild: m_sCurrentBetLabel];
        //-----------------------------------------------------
        
        
        
        
        //---------ADD EXIT MENU-------------------------------
        [CCMenuItemFont setFontName:@"Helvetica-BoldOblique"];
        [CCMenuItemFont setFontSize:36];
        m_Button_NewHand = [CCMenuItemFont itemFromString:NSLocalizedString(@"NewHand", @"") 
                                                   target:self 
                                                 selector:@selector(menuNewHandTouched:)];
		m_Button_NewHand.position =  CGPointMake(0, 0);
        
        // create the menu using the items
        m_MenuNewHand = [CCMenu menuWithItems:m_Button_NewHand, nil];
        m_MenuNewHand.position = CGPointMake(screenSize.width/2+ 400, screenSize.height/2+250);
        [self addChild:m_MenuNewHand];
        m_MenuNewHand.visible = false;
        
        m_ExitMenu = [CExitMenu node];
        [self addChild:m_ExitMenu];
        //------------------------------------------------------

        
		// must be enabled if you want to receive touch events!
		self.isTouchEnabled = YES;
	}
    [self scheduleUpdate];
	return self;
}

- (void) setPlayerButtons
{
    if (m_uiNumplayers > 2)
    {
        [m_Players[0] setDealer:true];
        [m_Players[1] setSmallBlind:true];
        [m_Players[2] setBigBlind:true];
    }
    else if (m_uiNumplayers == 2)
    {
        [m_Players[0] setDealer:true];
        [m_Players[0] setSmallBlind:true];
        [m_Players[1] setBigBlind:true];
    }
    
}

- (void) initPosPlayers
{
    unsigned int cont = 0;
    CGSize screenSize = [[CCDirector sharedDirector] winSize];
    
    //Insert players in clockwise order!!!
    
    //---Bottom player
    m_Players_Positions[cont] = CGPointMake((screenSize.width / 2), (screenSize.height / 2) - 320);
    m_Players_Orientations[cont] = 0.f;
    cont++;
    
    
    //---Left player
    m_Players_Positions[cont] = CGPointMake((screenSize.width / 2) - 430, (screenSize.height / 2));
    m_Players_Orientations[cont] = 90.f;
    cont++;
    
    
    //---Top player
    m_Players_Positions[cont] = CGPointMake((screenSize.width / 2), (screenSize.height / 2) + 320);
    m_Players_Orientations[cont] = 180.f;
    cont++;
    
    
    //---Right player
    m_Players_Positions[cont] = CGPointMake((screenSize.width / 2) + 430, (screenSize.height / 2));
    m_Players_Orientations[cont] = 270.f;
    cont++;
}

-(void) addPlayer:(TYPE_POKER_PLAYER)typePlayer Name:(NSString *) theName
{
    
    switch (typePlayer) 
    {
        case PokerPlayer_Local:
        {
            m_Players[m_uiNumplayers] = [[CLocalPlayer alloc] init];
        }
            break;
        case PokerPlayer_AI:
        {
             m_Players[m_uiNumplayers] = [[CAIPlayer alloc] init];
        }
            break;
        case PokerPlayer_Network:
        {
            m_Players[m_uiNumplayers] = [[CNetworkPlayer alloc] init];
        }
            break;
        default:
            break;
    }
    [m_Players[m_uiNumplayers] setRotationInfo:m_Players_Orientations[m_uiNumplayers]];
    [m_Players[m_uiNumplayers] setPositionInfo:m_Players_Positions[m_uiNumplayers]];
    [m_Players[m_uiNumplayers] setName:theName];
    [m_Players[m_uiNumplayers] setID:m_uiNumplayers];
    [m_Players[m_uiNumplayers] setPokerGame:self];
    
    [self addChild:m_Players[m_uiNumplayers]];
    
    
    m_uiNumplayers++;
}

-(void) ccTouchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{

    UITouch* touch = [touches anyObject];
    CGPoint location = [touch locationInView:[touch view]];
        
    CGSize screenSize = [[CCDirector sharedDirector] winSize];
    CGRect rectangle5 = CGRectMake((screenSize.height/2)-100, (screenSize.width / 2)-100 , 200, 200);
    
    //Accio quan es clica al centre de la pantalla. Tornen a entrar les communityCards
    if(CGRectContainsPoint(rectangle5, location))
    {
        //[m_pBoard insertCommunityCardSprites];
    }
}

-(void) ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    
    
}

-(void) menuNewHandTouched: (id) sender
{
    m_MenuNewHand.visible = false;
    [[SoundManager sharedInstance] playEffect:SOUND_BUTTON_NEXT];
    [self changeState:PokerState_NewHand];
    [self moveDelearAndBlind_Buttons];
}


//-------------------------------------------------------------------------
//---------------------UPDATE STATE MACHINE--------------------------------
//-------------------------------------------------------------------------
-(void) changeState:(TYPE_POKER_STATE) state
{
    m_StateMachine.m_eGameState         = state;
    m_StateMachine.m_bOnEnterFirstTime  = true;
    m_StateMachine.m_fStatesTime        = 0.f;
    m_StateMachine.m_uiCounterState     = 0;
}

-(void) update:(ccTime)delta
{

	switch (m_StateMachine.m_eGameState) 
    {
        case PokerState_NewHand: // <-- [Resetear una nueva mano]
        {
            if (m_StateMachine.m_bOnEnterFirstTime)
            {
                
                for(int card = 0; card < m_pBoard->m_CommunityCardsNumber; card++)
                {
                    [m_pBoard removeCommunityCard:(card)];
                }
                m_pBoard->m_uPositionIndex = 0;
               
                m_StateMachine.m_bOnEnterFirstTime = false;
                [m_StateMachine.m_sStateLabel setString:[NSString stringWithFormat:NSLocalizedString(@"PokerState_NewHand", @"")]];
                NSLog(@"POKER_STATE: NEW HAND");
               
                [self setBank:0];
                [self setCurrentBet:0];
                m_pBoard->m_CommunityCardsNumber = 0;
                [m_pDeck shareDeck];
                
                for(unsigned int i = 0; i < m_uiNumplayers; i++)
                {
                    //todo: reset players status...
                    [m_Players[i] resetStatus];
                }
                m_bFirstBet = true;
                [self changeState:PokerState_PreFlop];
                
            }
            else
            {
                //something to do for the next times...
            }
        }
            break;
            
        case PokerState_PreFlop: // <-- [Repartir las 2 cartas de cada jugador (hole cards)]
        {
            if (m_StateMachine.m_bOnEnterFirstTime)
            {
                m_StateMachine.m_bOnEnterFirstTime = false;
                [m_StateMachine.m_sStateLabel setString:[NSString stringWithFormat:NSLocalizedString(@"PokerState_PreFlop", @"")]];
                NSLog(@"POKER_STATE: PRE FLOP");
            }
            else
            { //something to do for the next times...
                
                m_StateMachine.m_fStatesTime += delta;
                if ( m_StateMachine.m_fStatesTime > PRE_FLOP_TIME_PLAYER)
                {
                    m_StateMachine.m_fStatesTime = 0;
                    if (m_StateMachine.m_uiCounterState < m_uiNumplayers)
                    {
                        int holeCard1 = [m_pDeck getCard];
                        int holeCard2 = [m_pDeck getCard];
//----------------------------------DEBUG_GAME_POKER----------------------        
#ifdef DEBUG_GAME_POKER
                        switch(m_StateMachine.m_uiCounterState)
                        {
                            case 0:
                                holeCard1 = 9;
                                holeCard2 = 20;
                                break;
                            case 1:
                                holeCard1 = 19;
                                holeCard2 = 3;
                                break;
                            case 2:
                                holeCard1 = 39;
                                holeCard2 = 40;
                                break;
                            case 3:
                                holeCard1 = 52;
                                holeCard2 = 53;
                                break;
                        }
#endif
//--------------------------------------------------------------------------
                        [m_Players[m_StateMachine.m_uiCounterState] setHoleCards:holeCard1 LeftCard:holeCard2];
                        m_StateMachine.m_uiCounterState++;
                    }
                    else
                    {
                        m_StateMachine.m_ePopGameState = PokerState_PostFlop_Flop;
                        [self changeState:PokerState_BettingRound];
                    }
                }

            } // END else m_bOnEnterFirstTime
            
        }
            break;
            
        case PokerState_PostFlop_Flop: // <-- [Repartir las 3 cartas comunas en el tapete (community cards)]
        {
            if (m_StateMachine.m_bOnEnterFirstTime)
            {
               m_StateMachine. m_bOnEnterFirstTime = false;
                [m_StateMachine.m_sStateLabel setString:[NSString stringWithFormat:NSLocalizedString(@"PokerState_PostFlop", @"")]];
                NSLog(@"POKER_STATE: POST FLOP");
            }
            else
            { //something to do for the next times...
                
                m_StateMachine.m_fStatesTime += delta;
                if ( m_StateMachine.m_fStatesTime > POST_FLOP_TIME_CARD)
                {
                    m_StateMachine.m_fStatesTime = 0;
                    if (m_StateMachine.m_uiCounterState < 3)
                    {
                        int communityCard = [m_pDeck getCard];
                        [m_pBoard setm_CommunityCardsValues:communityCard];
                        [m_pBoard showNewCommunityCard:communityCard];
                        m_StateMachine.m_uiCounterState++;
                    }
                    else
                    {
                        m_StateMachine.m_ePopGameState = PokerState_PostFlop_Turn;
                        [self changeState:PokerState_BettingRound];
                    }
                }
            } // END else m_bOnEnterFirstTime
            
        }
           
            break;
        case PokerState_PostFlop_Turn: // <-- [Repartir la cuarta carta comuna en el tapete (community cards)]
        {
            if (m_StateMachine.m_bOnEnterFirstTime)
            {
                m_StateMachine.m_bOnEnterFirstTime = false;
                [m_StateMachine.m_sStateLabel setString:[NSString stringWithFormat:NSLocalizedString(@"PokerState_PostFlopTurn", @"")]];
                NSLog(@"POKER_STATE: POST FLOP TURN");
                int communityCard4 = [m_pDeck getCard];
                [m_pBoard setm_CommunityCardsValues:communityCard4];
                [m_pBoard showNewCommunityCard:communityCard4];
            }
            else
            { //something to do for the next times...
                
                m_StateMachine.m_ePopGameState = PokerState_PostFlop_River;
                [self changeState:PokerState_BettingRound];
            } // END else m_bOnEnterFirstTime
        }
            break;
        case PokerState_PostFlop_River: //[Repartir la quinta carta comuna en el tapete (community cards)]
        {
            if (m_StateMachine.m_bOnEnterFirstTime)
            {
                m_StateMachine.m_bOnEnterFirstTime = false;
                [m_StateMachine.m_sStateLabel setString:[NSString stringWithFormat:NSLocalizedString(@"PokerState_PostFlopRiver", @"")]];
                NSLog(@"POKER_STATE: POST FLOP RIVER");
            }
            else
            {  //something to do for the next times...
               
                m_StateMachine.m_fStatesTime += delta;
                if ( m_StateMachine.m_fStatesTime > POST_FLOP_RIVER_TIME_CARD)
                {
                    m_StateMachine.m_fStatesTime = 0.f;
                    int communityCard5 = [m_pDeck getCard];
                    [m_pBoard setm_CommunityCardsValues:communityCard5];
                    [m_pBoard showNewCommunityCard:communityCard5];
                    m_StateMachine.m_ePopGameState = PokerState_ShowDown;
                    [self changeState:PokerState_BettingRound];
                }
            } // END else m_bOnEnterFirstTime
        }
            break;
        case PokerState_BettingRound: // <-- [Ronda de apuestas]
        {
            if (m_StateMachine.m_bOnEnterFirstTime)
            {
                m_StateMachine.m_bOnEnterFirstTime = false;
                [m_StateMachine.m_sStateLabel setString:[NSString stringWithFormat:NSLocalizedString(@"PokerState_BettingRound", @"")]];
                NSLog(@"POKER_STATE: Betting Round");
                m_bFirstRound = true;
                m_StateMachine.m_uiCounterState = [self findSmallBlind];                 
            }
            else
            { //something to do for the next times...
                            
                if (([m_Players[m_StateMachine.m_uiCounterState] getPlayerState] != PlayerState_Fold)      &&
                    ([m_Players[m_StateMachine.m_uiCounterState] getPlayerState] != PlayerState_AllIn)     &&
                    ([m_Players[m_StateMachine.m_uiCounterState] getPlayerState] != PlayerState_NoMoney))
                {
                    bool isEndBet = [m_Players[m_StateMachine.m_uiCounterState] check:m_uiCurrentBet deltaTime:delta firstBet:m_bFirstBet];
                    
                    if (isEndBet)
                    {
                        if ([m_Players[m_StateMachine.m_uiCounterState] isBigBlind])
                        {
                            m_bFirstBet = false;
                        }
                        unsigned int toBank = [m_Players[m_StateMachine.m_uiCounterState] getToBank];
                        [self setCurrentBet:m_uiCurrentBet + [m_Players[m_StateMachine.m_uiCounterState] getRaise]];
                        [self setBank:m_uiBank + toBank];
                        [self betNextPlayer];
                    }
                }
                else
                {
                    [self betNextPlayer];
                }
                
                
                [m_StateMachine.m_sStateLabel setString:[NSString stringWithFormat:@"%@ %i", NSLocalizedString(@"PokerState_BettingRoundP", @""), m_StateMachine.m_uiCounterState]];
                
            } // END else m_bOnEnterFirstTime
        }
            break;  
        case PokerState_AllIn: // <-- [bla bla bla..]
        {
            if (m_StateMachine.m_bOnEnterFirstTime)
            {
                m_StateMachine.m_bOnEnterFirstTime = false;
                [m_StateMachine.m_sStateLabel setString:[NSString stringWithFormat:NSLocalizedString(@"PokerState_AllIn", @"")]];
                NSLog(@"POKER_STATE: ALL IN");
            }
            else
            {
                //something to do for the next times...
                m_StateMachine.m_fStatesTime += delta;
                if ( m_StateMachine.m_fStatesTime > POST_ALLIN_TIME_CARD)
                {
                    m_StateMachine.m_fStatesTime = 0;
                    if (m_pBoard->m_CommunityCardsNumber < 5)
                    {
                        int communityCard = [m_pDeck getCard];
                        
//----------------------------------DEBUG_GAME_POKER----------------------
#ifdef DEBUG_GAME_POKER
                        switch (m_pBoard->m_CommunityCardsNumber) 
                        {
                            case 0:
                                communityCard = 30;
                                break;
                            case 1:
                                communityCard = 2;//31
                                break;
                            case 2:
                                communityCard = 32;
                                break;
                            case 3:
                                communityCard = 21;
                                break;
                            case 4:
                                communityCard = 53;
                                break;
                        }
#endif
//--------------------------------------------------------------------------
                        [m_pBoard setm_CommunityCardsValues:communityCard];
                        [m_pBoard showNewCommunityCard:communityCard];
                    }
                    else
                    {
                        [self changeState:PokerState_ShowDown];
                    }
                }

            } // END else m_bOnEnterFirstTime
            
            //todo...
        }
            break;
        case PokerState_ShowDown: // <-- [Se realiza animacion de mostrar cartas de los jugadores]
        {
            if (m_StateMachine.m_bOnEnterFirstTime)
            {
                m_StateMachine.m_bOnEnterFirstTime = false;
                [m_StateMachine.m_sStateLabel setString:[NSString stringWithFormat:NSLocalizedString(@"PokerState_ShowDown", @"")]];
                NSLog(@"POKER_STATE: SHOW DOWN");
            }
            else
            {
                //something to do for the next times...
                m_StateMachine.m_fStatesTime += delta;
                if ( m_StateMachine.m_fStatesTime > SHOW_DOWN_TIME )
                {
                    m_StateMachine.m_fStatesTime = 0;
                    if (m_StateMachine.m_uiCounterState < m_uiNumplayers)
                    {
                        if (([m_Players[m_StateMachine.m_uiCounterState] getPlayerState] != PlayerState_Fold) &&
                            ([m_Players[m_StateMachine.m_uiCounterState] getPlayerState] != PlayerState_NoMoney))
                        {
                            [m_Players[m_StateMachine.m_uiCounterState] showCards];
                        }
                        m_StateMachine.m_uiCounterState++;
                    }
                    else
                    {
                        [self changeState:PokerState_WinnerHand];
                    }
                }
            } // END else m_bOnEnterFirstTime
        }
            break;
        case PokerState_WinnerHand: // <-- [Se analiza el ganador/ganadores de la apuesta y se reparte el dinerito]
        {
            if (m_StateMachine.m_bOnEnterFirstTime)
            {
                m_StateMachine.m_bOnEnterFirstTime = false;
                [m_StateMachine.m_sStateLabel setString:[NSString stringWithFormat:NSLocalizedString(@"PokerState_WinnerHand", @"")]];
                NSLog(@"POKER_STATE: WINNER HAND"); 
                [self whoWins];
                
            }
            else
            {
                //something to do for the next times...
                m_StateMachine.m_fStatesTime += delta;
                if ( m_StateMachine.m_fStatesTime > POST_NEW_HAND )
                {
                    [m_StateMachine.m_sStateLabel setString:[NSString stringWithFormat:
                                                             NSLocalizedString(@"PokerState_WinnerHandB", @"")]];
                    m_MenuNewHand.visible = true;
                }
                else
                {
                    [m_StateMachine.m_sStateLabel setString:[NSString stringWithFormat:
                                                             @"%@%f)",NSLocalizedString(@"PokerState_WinnerHandA", @""), POST_NEW_HAND - m_StateMachine.m_fStatesTime]];
                }
            } // END else m_bOnEnterFirstTime
        }
            break;
        case PokerState_WinTheGame: // <-- [bla bla bla..]
        {
            if (m_StateMachine.m_bOnEnterFirstTime)
            {
                m_StateMachine.m_bOnEnterFirstTime = false;
                [m_StateMachine.m_sStateLabel setString:[NSString stringWithFormat:NSLocalizedString(@"PokerState_WinTheGame", @"")]];
                NSLog(@"POKER_STATE: WIN THE GAME");   
            }
            else
            {
                //something to do for the next times...
            } // END else m_bOnEnterFirstTime
        }
            break;
        case PokerState_LoseTheGame: // <-- [bla bla bla..]
        {
            if (m_StateMachine.m_bOnEnterFirstTime)
            {
                m_StateMachine.m_bOnEnterFirstTime = false;
                [m_StateMachine.m_sStateLabel setString:[NSString stringWithFormat:NSLocalizedString(@"PokerState_LoseTheGame", @"")]];
                NSLog(@"POKER_STATE: LOSE THE GAME");
            }
            else
            {
                //something to do for the next times...
            } // END else m_bOnEnterFirstTime
        }
            break;

        default:
        {
            if (m_StateMachine.m_bOnEnterFirstTime)
            {
                m_StateMachine.m_bOnEnterFirstTime = false;
                NSLog(@"POKER_STATE_ERROR!: unknown state");
            }
            else
            {
                //something to do for the next times...
            } // END else m_bOnEnterFirstTime
        }
            break;
    }
}
//---------------------END UPDATE STATE MACHINE--------------------------------
//-----------------------------------------------------------------------------


-(void) whoWins
{

    NSLog(@"ENTREM A WHOWINS");


    for( int i = 0; i < m_uiNumplayers; i++)
    {
        [m_Players[i] setm_AllCardValuesCont:(0)];
        
        for(int card = 0; card < m_pBoard->m_CommunityCardsNumber; card++)
        {
            [m_Players[i] setCardValues:(m_pBoard->m_CommunityCardsValues[card])];
        }
        [m_Players[i] setCardValues:([m_Players[i] getHoleCard1])];
        [m_Players[i] setCardValues:([m_Players[i] getHoleCard2])];
         
        //posar les cartes manualment per debugar!!!!
    }
    
    
    //mostra per consola les cartes
    for( int i = 0; i < m_uiNumplayers; i++)
    {
        /*for(int j = 0; j < m_pBoard->m_CommunityCardsNumber+2; j++)
        {
            NSLog(@"A - player %i carta %i: %i ",i,j,[m_Players[i] getNumCard:([m_Players[i] getCard:(j)])]);
        }*/
        
       
        [m_Players[i] orderHighestCards];
        [m_Players[i] setBestHandValue];
        
        /*for(int j = 0; j < m_pBoard->m_CommunityCardsNumber+2; j++)
        {
            NSLog(@"B- player %i carta %i: %i ",i,j,[m_Players[i] getNumCard:([m_Players[i] getCard:(j)])]);
        }*/
        
        /*NSLog(@"========== player %i ===========",i);
        NSLog(@"m_HandValue.hand_value_primary: %i",m_Players[i]->m_HandValue.hand_value_primary);
        NSLog(@"m_HandValue.hand_value_secondary: %i",m_Players[i]->m_HandValue.hand_value_secondary);
        NSLog(@"m_HandValue.hand_value_third: %i",m_Players[i]->m_HandValue.hand_value_third);
        NSLog(@"m_HandValue.hand_value_fourth: %i",m_Players[i]->m_HandValue.hand_value_fourth);
        NSLog(@"m_HandValue.hand_value_fith: %i",m_Players[i]->m_HandValue.hand_value_fith);
        NSLog(@"m_HandValue.flush_figure: %i",m_Players[i]->m_HandValue.flush_figure);
        NSLog(@"m_HandValue.left: %i",m_Players[i]->m_HandValue.left);
        NSLog(@"m_HandValue.left: %i",m_Players[i]->m_HandValue.left);*/
        
        [m_ConditionGame setNumPlayers:m_uiNumplayers];
        [m_ConditionGame setmPlayers:m_Players[i] index:i];
        [m_ConditionGame setBank:m_uiBank];
        
    }
    [m_ConditionGame run];
    for(int i = 0; i < m_uiNumplayers; i++)
    {
        //Actualizem tots els Labels del Board
        NSLog(@"POKERTEXASHOLDEM - Player %i m_HandValue.win_hand: %i",i, m_Players[i]->m_HandValue.win_hand);
        if(m_Players[i]->m_HandValue.win_hand == true){
            //posem les lletres dels diners en verd durant 3 segons
            [m_Players[i] setGain:(m_Players[i]->m_uiGain)];
        }else{
            //posem les lletres dels diners en vermell durant 3 segons
             [m_Players[i] setLose:(m_Players[i]->m_uiGain)];
        }
        [m_Players[i] setMoney:(m_Players[i]->m_uiMoney)];
    }
        
    
    
    NSLog(@"SORTIM DE WHOWINS I EXIT");
}


-(void) betNextPlayer
{
    m_StateMachine.m_uiCounterState = (m_StateMachine.m_uiCounterState+1) % m_uiNumplayers;
    
    if ([m_Players[m_StateMachine.m_uiCounterState] isSmallBlind])
    {
        m_bFirstRound = false;
    }
    
    //Si hi ha un jugador diferent de fold,allin,nomoney amb currentBet < m_uiCurrentBet hem de continuar apostant:
    //Si hi ha un jugador diferent de fold,allin,nomoney amb currentBet = m_uiCurrentBet i es m_bFirstRound hem de continuar apostant:
    unsigned int AllinState         = 0;
    unsigned int AllSameBet         = 0;
    unsigned int Fold_NoMoneyState  = 0;
    
    bool existBetPlayer = false;
    for( int i = 0; i < m_uiNumplayers; i++)
    {
        if ([m_Players[i] getPlayerState] == PlayerState_AllIn)
        {
            AllinState++;
        }
        else if (([m_Players[i] getPlayerState] == PlayerState_Fold)      ||
                 ([m_Players[i] getPlayerState] == PlayerState_NoMoney))
        {
            Fold_NoMoneyState++;
        }
        else
        {
            AllSameBet++;
            if (([m_Players[i] getCurrentBet] < m_uiCurrentBet) ||
                (m_bFirstRound && [m_Players[i] getCurrentBet] == m_uiCurrentBet))
            {
                existBetPlayer = true;      
            }
        }
    }//END for each player
    
    
    if (existBetPlayer && (Fold_NoMoneyState + 1 == m_uiNumplayers))
    {
        // - Si tots menys 1 estan en fold, nomoney-> PokerState_WinnerHand
        [self changeState:PokerState_WinnerHand];
    }
    
    if (!existBetPlayer)
    {
        if (Fold_NoMoneyState + 1 == m_uiNumplayers)
        {
            // - Si tots menys 1 estan en fold, nomoney-> PokerState_WinnerHand
            [self changeState:PokerState_WinnerHand];
        }
        else if (AllinState>1 && AllSameBet<2)
        {
            // - Si hi més d'un allIn i només un o zero amb aposta actual -> PokerState_AllIn
            [self changeState:PokerState_AllIn];
        }
        else
        {
            [self changeState:m_StateMachine.m_ePopGameState];
        }
    }

}
-(int) findDelear
{
    for( int i = 0; i < m_uiNumplayers; i++)
    {
        if ([m_Players[i] isDelear])
        {
            return i;
        }
    }
    NSLog(@"ERROR in findDelear!!!. Nobody is dealer");
    return 0;
}

-(int) findSmallBlind
{
    for( int i = 0; i < m_uiNumplayers; i++)
    {
        if ([m_Players[i] isSmallBlind])
        {
            return i;
        }
    }
    NSLog(@"ERROR in findSmallBlind!!!. Nobody is smallBlind");
    return 0;
}

-(int) findBigBlind
{
    for( int i = 0; i < m_uiNumplayers; i++)
    {
        if ([m_Players[i] isBigBlind])
        {
            return i;
        }
    }
    NSLog(@"ERROR in findBigBlind!!!. Nobody is bigBlind");
    return 0;
}

-(void) moveDelearAndBlind_Buttons
{
    
    bool l_bFind;
    int index_delear = [self findDelear];
    [m_Players[index_delear] setDealer:false];
    l_bFind = false;
    while (!l_bFind)
    {
        index_delear = (index_delear+1) % m_uiNumplayers;
        if ([m_Players[index_delear] getPlayerState] != PlayerState_NoMoney)
        {
            l_bFind = true;
            [m_Players[index_delear] setDealer:true];
        }
    }
    
    int index_smallB = [self findSmallBlind];
    [m_Players[index_smallB] setSmallBlind:false];
    l_bFind = false;
    while (!l_bFind)
    {
        index_smallB = (index_smallB+1) % m_uiNumplayers;
        if ([m_Players[index_smallB] getPlayerState] != PlayerState_NoMoney)
        {
            l_bFind = true;
            [m_Players[index_smallB] setSmallBlind:true];
        }
    }
    
    
   
    int index_bigB = [self findBigBlind];
    [m_Players[index_bigB] setBigBlind:false];
    l_bFind = false;
    while (!l_bFind)
    {
        index_bigB = (index_bigB+1) % m_uiNumplayers;
        if ([m_Players[index_bigB] getPlayerState] != PlayerState_NoMoney)
        {
            l_bFind = true;
            [m_Players[index_bigB] setBigBlind:true];
        }
    }
    
    
}

-(unsigned int) getBank
{
    return m_uiBank;
}

-(void) setBank:(unsigned int) bank
{
    m_uiBank = bank;
    [m_sBankLabel setString:[NSString stringWithFormat:@"%@%d $", NSLocalizedString(@"Bank", @""), m_uiBank]];
}

-(void) setCurrentBet:(unsigned int) currentBet
{
    m_uiCurrentBet = currentBet;
    [m_sCurrentBetLabel setString:[NSString stringWithFormat:@"%@%d $", NSLocalizedString(@"CurrentBet", @""), m_uiCurrentBet]];
}

- (void) changePlayerType:(unsigned int) playerId TypeOfPlayer:(TYPE_PLAYER) type
{
    CPlayer* l_newPlayer = NULL;
    switch (type) 
    {
        case PokerPlayer_Local:
        {
            l_newPlayer = [[CLocalPlayer alloc] init];
        }
            break;
        case PokerPlayer_AI:
        {
            l_newPlayer = [[CAIPlayer alloc] init];
        }
            break;
        case PokerPlayer_Network:
        {
            l_newPlayer = [[CNetworkPlayer alloc] init];
        }
            break;
        default:
            break;
    }
    
    [l_newPlayer cloningData:m_Players[playerId]];
    [self removeChild:m_Players[playerId] cleanup:true];
    m_Players[playerId] = l_newPlayer;
    [self addChild:m_Players[playerId]];
}

// on "dealloc" you need to release all your retained objects
-(void) dealloc
{
    for(unsigned int cont = 0; cont < m_uiNumplayers; cont++)
    {
        //[m_Players[cont] release];
    }
    
	//[m_pBoard release];
	//[m_pDeck release];
	// don't forget to call "super dealloc"
	[super dealloc];
}



@end
